<?php

require_once 'SmartL/Zend/Controller/Action.php';
require_once 'SmartL/Zend/Form.php';
require_once 'Zend/Form/Element/Text.php';
require_once 'Zend/Form/Element/Textarea.php';
require_once 'Zend/Form/Element/Select.php';
require_once 'Zend/Form/Element/Hidden.php';
require_once 'Zend/Form/Element/File.php';
require_once 'Zend/Form/Element/Submit.php';
require_once 'Zend/Form/SubForm.php';
require_once 'Db/Shop/Record/Product.php';
require_once 'Db/Shop/Record/Category.php';
require_once 'Db/Shop/Record/BasketItem.php';
require_once 'SmartL/Zend/Paginator/Adapter/Doctrine.php';
require_once 'Zend/Paginator.php';

class Admin_ProductsController extends SmartL_Zend_Controller_Action
{
    public function listAction ()
    {
        // Parametry: stránka = 1
        $query = new Doctrine_Query();
        $query->parseDqlQuery($this->config->getAction("list")->getSelection("list")->getDql('Db_Shop_Record_Product'));
        $products = new Zend_Paginator( new SmartL_Zend_Paginator_Adapter_Doctrine($query, Doctrine::HYDRATE_RECORD) );
        $products->setCurrentPageNumber($this->_getParam('page'));
        $products->setItemCountPerPage(10);
        $this->view->products = $products;
    }
    public function addProductAction ()
    {
    	//die($this->translations['form-product']->getLocale());
        // Parametry?: název, popis, obrázek, cena, kategorie                
        $form = SmartL_Zend_Form::getForm(array("name" => "product" , "method" => "post", "enctype"=>"multipart/form-data"),
        		$this->translations['form-product']);        
        $hidden = new Zend_Form_Element_Hidden("addProduct");
        $submit = new Zend_Form_Element_Submit("send");
        $submit->setLabel("Send");
        $form->addElement($hidden);
        $form->setAction($this->_helper->url->url(array("action"=>"add-product","controller"=>"products")));        
        
        $productSubForm = SmartL_Zend_Form::getForm($this->config->getAction("addProduct")->getForm("product"), 
        	null, 'Zend_Form_SubForm');
        $productSubForm->category->options = $this->_getCategoriesOptions();
        
        $textsSubForm = SmartL_Zend_Form::getForm( $this->config->getAction("addProduct")->getForm("product-texts"),
        	null, 'Zend_Form_SubForm');
        $textsSubForm->getDecorator('Fieldset')
        	->setOption("legend", $this->translations['fieldsets']->translate("Texts")
        	." ".Zend_Registry::get('shopDefaultLanguage')->getLanguageName()
        	."-".Zend_Registry::get('shopDefaultLanguage')->getCultureName());
        
        $form->addSubForm($productSubForm, "product")
             ->addSubForm($textsSubForm, "texts")
             ->addElement($submit);
             
        $this->view->form = $form;
        if (isset($_POST['addProduct'])) {
            if ($form->isValid($_POST) and $form->product->image->receive()) {
                $product = new Db_Shop_Record_Product();
                //forms
                $values = $form->getSubForm("product")->getValues();
                $values = $values['product'];
                $texts = $form->getSubForm("texts")->getValues();
                $texts = $texts['texts'];
                //product 
                $product->price = (float)$values['price'];
                $product->categoryId = $values['category'];
                //images     
                if ( isset($_FILES['image']['name']) and $_FILES['image']['name'] !== "") {                	
                    $this->_setProductImage($product, $_FILES['image']['tmp_name'], $_FILES['image']['name']);  		
                }
                //product-texts
                $languageId = Zend_Registry::get('shopDefaultLanguage')->getId();
                $product->Translation[$languageId]->name = $texts['name'];
                $product->Translation[$languageId]->description = $texts['description'];
                $product->save();
                $this->_helper->redirector->goto("list", "products");
            }
        }
    }
    public function editProductAction ()
    {
        // Parametry?: id produktu, název, popis, obrázek, cena, kategorie                
        $this->view->productForm = $productForm = $this->_createEditProductForm();
        $this->view->textsForm = $textsForm = $this->_createEditProductTextsForm();
        
        $textsForm->setAction($this->_helper->url->url(array("action"=>"edit-product","controller"=>"products")));              
        $productForm->setAction($this->_helper->url->url(array("action"=>"edit-product","controller"=>"products")));
        
        $this->view->languages = Zend_Registry::get("shopLanguages");
        $id = $this->_hasParam("id") ? $this->_getParam('id') : null;
        if (isset($_POST['languageId'])) {
            $this->_processEditProductTextsForm($textsForm);
            $id = $textsForm->productId->getValue();
        } else if (isset($_POST['productId'])) {
            $this->_processEditProductForm($productForm);
            $id = $productForm->productId->getValue();
        }
        $product = Doctrine_Manager::getInstance()->getCurrentConnection()->getTable('Db_Shop_Record_Product')->find($id);
        $productForm->productId->setValue($product->id);
        $textsForm->productId->setValue($product->id);
        if (isset($_POST['languageId']) or ! isset($_POST['productId'])) {
            $productForm->price->setValue((float)$product->price);
            $productForm->category->setValue($product->categoryId);
        }
        if (! isset($_POST['languageId'])) {
            $textsForm->languageId->setValue(Zend_Registry::get("shopDefaultLanguage")->getId());
            $this->_fillTextsForm($textsForm, $product, $textsForm->languageId->getValue());
        }
	    $this->view->product_id = $id;
    }
    public function productTextsAjaxAction ()
    {
        if ($this->_hasParam('id') and $this->_hasParam('langId')) {
            $query = new Doctrine_Query();
            $product = $query->from('Db_Shop_Record_Product p')->select('*')->where('p.id = ?', $this->_getParam('id'))->execute()->getFirst();
            $languageId = $this->_getParam('langId');
            $this->_helper->json->direct(array("name" => $product->Translation[$languageId]->name , "description" => $product->Translation[$languageId]->description));
        }
    }
    public function removeProductAction ()
    {
        // Parametry: id produktu
        if ($this->_hasParam("id")) {
            $query = new Doctrine_Query();
			$product = Doctrine_Manager::getInstance()->getCurrentConnection()->getTable('Db_Shop_Record_Product')
					->find($this->_getParam('id'));
			$this->_deleteProductImages($product);                 
            $query->delete()->from('Db_Shop_Record_Product p')->where('p.id = ?', $this->_getParam('id'))->execute();
            $this->_helper->redirector->goto("list", "products");
        }
    }
    private function _processEditProductForm ($form)
    {
        if ($form->isValid($_POST)) {
			$product = Doctrine_Manager::getInstance()->getCurrentConnection()->getTable('Db_Shop_Record_Product')
				->find($form->productId->getValue());        	
            $product->price = $form->price->getValue();
            $product->categoryId = $form->category->getValue();
			if ( isset($_FILES['image']['name']) and $_FILES['image']['name'] !== "") {
				$filename = $form->image->getFilename();
				if ( !file_exists($filename) ) $filename = $_FILES['image']['tmp_name']; 
				$this->_deleteProductImages($product);
				$this->_setProductImage($product, $filename, $_FILES['image']['name']);
			}
			$product->save();
        }
    }
    private function _processEditProductTextsForm ($form)
    {
        if ($form->isValid($_POST)) {
            $values = $form->getValues();
            $product = Doctrine_Manager::getInstance()->getCurrentConnection()->getTable('Db_Shop_Record_Product')->find($values['productId']);
            $product->Translation[$values['languageId']]->name = $values['name'];
            $product->Translation[$values['languageId']]->description = $values['description'];
            $product->save();
        }
    }
    private function _createEditProductTextsForm ()
    {
    	$options = $this->config->getAction("addProduct")->getForm("product-texts");
        $options['elements']['languageId'] = array("type" => "hidden");
        $options['elements']['productId'] = array("type" => "hidden");
        $options['elements']['submit'] = array("type" => "submit" , "options" => array("label" => "Send"));
        $textsForm = SmartL_Zend_Form::getForm($options, $this->translations['form-product']);
        return $textsForm;
    }
    private function _createEditProductForm ()
    {
        $options = $this->config->getAction("addProduct")->getForm("product");
        $options['elements']['productId'] = array('type' => 'hidden');
        $options['elements']['submit'] = array("type" => "submit" , "options" => array("label" => "Send"));
        $productForm = SmartL_Zend_Form::getForm($options, $this->translations['form-product']);
        $productForm->category->options = $this->_getCategoriesOptions();
        return $productForm;
    }
    private function _fillTextsForm ($textsForm, $product, $languageId)
    {
        $textsForm->name->setValue($product->Translation[$languageId]->name);
        $textsForm->description->setValue($product->Translation[$languageId]->description);
    }
    private function _getCategoriesOptions ()
    {
        $query = new Doctrine_Query();
        $data = $query->from('Db_Shop_Record_Category c')->select('c.id')->execute();
        $result = array();
        foreach ($data as $category) {
            $result[$category->id] = $category->translate("name");
        }
        return $result;
    }
    
    private function _setProductImage($product, $tmpName, $imageName)
    {
        if ($imageName !== "" or $imageName !== null) {
        	$ds = DIRECTORY_SEPARATOR;
            $dir = $this->application->getBasePath() . $ds 
            		. $this->application->getPublicDir() 
            		. $ds . "Products" . $ds;    	
        	        		
            $imageName = basename($imageName);
            $i = "";
            $pathInfo = pathInfo($imageName);
            while( file_exists($dir . $pathInfo['filename'] . $i . '.' . $pathInfo['extension']) ) {
            	$i++;
            }
            $imageName = $pathInfo['filename'] . $i . '.' . $pathInfo['extension'];
            $product->image = $imageName; 
            move_uploaded_file($tmpName, $dir  . $imageName );
            $thumbConfig = $this->application->getConfig()->demo->products->thumb;
            $this->_createImageThumbnail($dir  . $imageName, $dir . "Thumbs" . $ds . $imageName,
            	$thumbConfig->maxWidth->getValue(), $thumbConfig->maxHeight->getValue() );
        }
    }
    
    
    private function _createImageThumbnail($image,$thumb,$max_thumb_width, $max_thumb_height)
    {
    	$info = pathinfo($image);
    	$extension = strtolower($info['extension']);
    	
    	if ( $extension == "jpg" or $extension=="jpeg") {
	    	$src_img = imagecreatefromjpeg($image);
    	}
    	else if ( $extension == "png" ) {
    		$src_img = imagecreatefrompng($image);  
    	}
    	if ( !isset($src_img) or $src_img === null ) {
    		copy($src_img, $thumb);
    		return;
    	}
    	
    	$orig_w = imagesx($src_img);
    	$orig_h = imagesy($src_img); 
    	if ( $orig_w >= $orig_h ) {
    		$thumb_width = $max_thumb_width;
    		$thumb_height = $max_thumb_width * ($orig_h/$orig_w);
    	}
    	else {
    		$thumb_height = $max_thumb_height;
    		$thumb_width = $max_thumb_height * ($orig_w/$orig_h);
    	}
    	
	    $dst_img = imagecreate($thumb_width,$thumb_height);
	    imagecopyresized($dst_img,$src_img,0,0,0,0,$thumb_width,$thumb_height,imagesx($src_img),imagesy($src_img));
	
	    if ( $extension == "jpg" or $extension=="jpeg") {
	    	imagejpeg($dst_img, $thumb);
	    }	    
	    else {
	    	imagepng($dst_img, $thumb);
	    }     	
    }
    
    private function _deleteProductImages($product)
    {
    	$ds = DIRECTORY_SEPARATOR;
        $dir = $this->application->getBasePath() . $ds 
        		. $this->application->getPublicDir() 
        		. $ds . "Products" . $ds;
        		
        $files = array($dir . $product->image, $dir . "Thumbs" . $ds . $product->image);
        foreach ($files as $file) {
        	if ( file_exists($file) ) {
        		unlink($file);
        	}
        }
    }
}

